package org.dfzt.modules.system.controller;


import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dfzt.common.api.vo.Result;
import org.dfzt.common.aspect.annotation.PermissionData;
import org.dfzt.common.constant.CommonConstant;
import org.dfzt.common.system.query.QueryGenerator;
import org.dfzt.common.system.service.ISysBaseAPI;
import org.dfzt.common.system.util.JwtUtil;
import org.dfzt.common.system.vo.LoginUser;
import org.dfzt.common.util.PmsUtil;
import org.dfzt.common.util.RedisUtil;
import org.dfzt.common.util.VerifyParam;
import org.dfzt.common.util.encryption.SMUtils;
import org.dfzt.common.util.oConvertUtils;
import org.dfzt.modules.system.entity.*;
import org.dfzt.modules.system.model.DepartIdModel;
import org.dfzt.modules.system.model.SysUserSysDepartModel;
import org.dfzt.modules.system.service.*;
import org.dfzt.modules.system.vo.SysDepartUsersVO;
import org.dfzt.modules.system.vo.SysUserRoleVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */

@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    private static final Log log = LogFactory.getLog(SysUserController.class);
    @Value(value = "${adminId:e9ca23d68d884d4ebb19d07889727dae}")
    private String adminId;
    @Value(value = "${configId:1277412059420295169}")
    private String configId;
    @Value(value = "${auditId:1277413732465246209}")
    private String auditId;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private ISysDepartRoleUserService departRoleUserService;

    @Autowired
    private ISysDepartRoleService departRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private ISysUserAgentService userAgentService;

    @Resource
    private ISysRoleService sysRoleService;

    @Value("${dfzt.path.upload}")
    private String upLoadPath;

    /**
     * 获取用户列表数据
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/list")
    public Result<IPage<SysUser>> queryPageList(SysUser user,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        if(!VerifyParam.verifyParam("SysUser",user,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne("username","_reserve_user_external");
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
        pageList.getRecords().forEach(i -> {
            Set<String> keys = redisUtil.getKeys(i.getUsername());
            if (keys.isEmpty()){
                i.setIsOnline(1);
            } else {
                i.setIsOnline(0);
            }
        });

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
        if(userIds!=null && userIds.size()>0){
            Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item->{
                //TODO 临时借用这个字段用于页面展示
                item.setOrgCode(useDepNames.get(item.getId()));
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/add")
    public Result<SysUser> add(@RequestBody JSONObject item) {
        SMUtils.decryptJSONObject(item);
        Result<SysUser> result = new Result<SysUser>();
        String selectedRoles = item.getString("selectedroles");
        String selectedDeparts = item.getString("selecteddeparts");
        try {
            SysUser optor = JSON.parseObject(item.toJSONString(), SysUser.class);
            if(!VerifyParam.verifyParam("SysUser",optor,"object")){
                result.error500("数据范围验证失败！");
                return result;
            }
            if(sysUserService.isExist(optor)){
                result.error500("该账号重要信息不唯一！");
                return result;
            }
            if(!SMUtils.compareTwoPWD(optor.getPassword(),item.getString("confirmPassword"))){
                result.error500("两次输入密码不一致！");
                return result;
            }
            //验证密码是否包含用户名 false为不包含
            if (SMUtils.checkPwdContainsUsername(optor.getPassword(),optor.getUsername())){
                result.error500("密码不能与用户名相同或包含用户名");
                return result;
            }
            if(!IdcardUtil.isValidCard(optor.getIdCard())){
                result.error500("身份证号不合法！");
                return result;
            }
            if (!compareTime(optor.getUserLoginTimeQuantum())){
                result.error500("日期格式不合法！");
                return result;
            }
            if (StringUtils.isNotEmpty(optor.getWorkNo())){
                List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getWorkNo, optor.getWorkNo()));
                if (!list.isEmpty()){
                    result.error500("工号已存在！");
                    return result;
                }
            }
            optor.setSex(IdcardUtil.getGenderByIdCard(optor.getIdCard()));
            optor.setBirthday(IdcardUtil.getBirthDate(optor.getIdCard()));
            optor.setStatus(1);
            optor.setDelFlag(CommonConstant.DEL_FLAG_0);
            optor.setCreateTime(new Date());//设置创建时间
            optor.setNeedUpdatePw("1");

            sysUserService.addUserWithRole(optor, selectedRoles);
            sysUserService.addUserWithDepart(optor, selectedDeparts);
            result.success("添加成功！");
            sysBaseAPI.addLog( "用户"+ optor.getUsername()+"添加成功", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_SUCCESS, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
            sysBaseAPI.addLog("用户添加失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_FAIL, null);
        }
        return result;
    }

    /**
     * @description: 比较时间大小
     * @param time 1
     * @return boolean
     * @author cuiyf
     * @date 2020/6/29 11:57
     */
    private static boolean compareTime(String time){
        if (StringUtils.isBlank(time)){
            return false;
        }
        try {
            String[] split = time.split("~");

            if (StringUtils.isBlank(split[0]) || StringUtils.isBlank(split[1])){
                return false;
            }

            if(split[0].contains(":") || split[1].contains(":")){
                String[] arr1 = split[0].split(":");
                int total1 = Integer.parseInt(arr1[0])*3600 + Integer.parseInt(arr1[1])*60 + Integer.parseInt(arr1[2]);
                String[] arr2 = split[1].split(":");
                int total2 = Integer.parseInt(arr2[0])*3600 + Integer.parseInt(arr2[1])*60 + Integer.parseInt(arr2[2]);
                return total2 - total1 > 0;
            }
        } catch (Exception e){
            log.error("比较时间异常：",e);
        }
        return false;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/edit")
    public Result<SysUser> edit(@RequestBody JSONObject jsonObject) {
        SMUtils.decryptJSONObject(jsonObject);
        Result<SysUser> result = new Result<SysUser>();
        try {
            String loginUserPassword = jsonObject.getString("loginUserPassword");
            if(StringUtils.isBlank(loginUserPassword)){
                result.error500("当前登录用户密码不能为空！");
                return result;
            }
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (!SMUtils.compareTwoPWD(jsonObject.getString("loginUserPassword"),loginUser.getPassword())){
                sysBaseAPI.addLog("用户"+ loginUser.getUsername()+"更新用户信息失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, loginUser.getUsername());
                return result.error500("当前登录用户密码不正确!");
            }
            jsonObject.remove("loginUserPassword");
            SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
            if(sysUser==null) {
                result.error500("未找到对应实体");
            }else {
                SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
                if(!VerifyParam.verifyParam("SysUser",user,"object")){
                    result.error500("数据范围验证失败！");
                    return result;
                }
                if (!compareTime(user.getUserLoginTimeQuantum())){
                    result.error500("时间格式不合法！");
                    return result;
                }
                user.setUpdateTime(new Date());
                //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), sysUser.getSalt());
                user.setPassword(sysUser.getPassword());
                String roles = jsonObject.getString("selectedroles");
                String departs = jsonObject.getString("selecteddeparts");
                sysUserService.editUserWithRole(user, roles);
                sysUserService.editUserWithDepart(user, departs);
                sysUserService.updateNullPhoneEmail();
                result.success("修改成功!");
                sysBaseAPI.addLog("用户"+ user.getUsername()+"修改成功", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_SUCCESS, null);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
            sysBaseAPI.addLog("用户更新失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, null);

        }
        return result;
    }

    /**
     * 删除用户
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        Result<SysUser> result = new Result<>();
        if(!VerifyParam.verifyParam("id",id,"SysUser")){
            result.error500("数据范围验证失败！");
            return result;
        }
        //查询到用户后判断是否是管理员用户
        if(id.equals(adminId) || id.equals(configId) || id.equals(auditId)){
            result.error500("禁止注销系统账号！");
            return result;
        }
        SysUser sysUser = sysUserService.getById(id);
        if(sysUser==null) {
            result.error500("未找到对应实体");
            log.error("未找到对应实体类，注销失败！");
//            sysBaseAPI.addLog("用户"+ sysUser.getUsername()+"删除失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_FAIL, null);
        }else {
            // 当某个用户被删除时,删除其ID下对应的部门数据
            boolean ok = sysUserService.removeById(id);
            //sysUserDepartService.remove(new LambdaQueryWrapper<SysUserDepart>().eq(SysUserDepart::getUserId, id));
            //sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id));
            if(ok) {
                result.success("注销成功!");
                sysBaseAPI.addLog("用户"+ sysUser.getUsername()+"注销成功", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_SUCCESS, null);
            }
        }
        return result;
    }

    /**
     * 批量删除用户
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        String[] arr = ids.split(",");
        for (String id : arr){
            //查询到用户后判断是否是管理员用户
            if(id.equals(adminId) || id.equals(configId) || id.equals(auditId)){
                return Result.error("禁止注销系统账号！");
            }
        }

        if(!VerifyParam.verifyParam("ids",ids)){
            return Result.error("数据范围验证失败！");
        }
        this.sysUserService.deleteBatchUsers(ids);

        // 当某个用户被删除时,删除其ID下对应的部门数据
        //sysUserDepartService.remove(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, Arrays.asList(ids.split(","))));
        //sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, Arrays.asList(ids.split(","))));
        return Result.ok("批量删除用户成功");
    }


    /**
     * 冻结&解冻用户
     * @param jsonObject
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/frozenBatch")
    public Result<SysUser> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        if(!VerifyParam.verifyParam("SysUser",jsonObject,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("status");
            String[] arr = ids.split(",");
            for (String id : arr) {
                //查询到用户后判断是否是管理员用户
                if(id.equals(adminId) || id.equals(configId) || id.equals(auditId)){
                    result.error500("禁止冻结系统账号！");
                    return result;
                }
                if(oConvertUtils.isNotEmpty(id)) {
                    SysUser sysUser = new SysUser();
                    sysUser.setStatus(Integer.parseInt(status));
                    this.sysUserService.update(sysUser,
                            new UpdateWrapper<SysUser>().lambda().eq(SysUser::getId,id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败"+e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }

    /**
     * 激活用户
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/handleActivate", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/handleActivate")
    public Result<SysUser> handleActivate(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<>();
        if(!VerifyParam.verifyParam("SysUser",jsonObject,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("status");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if(oConvertUtils.isNotEmpty(id)) {
                    this.sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                            .set(SysUser::getStatus,Integer.parseInt(status))
                            .eq(SysUser::getId,id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败"+e.getMessage());
        }
        result.success("操作成功!");
        return result;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/queryById")
    public Result<SysUser> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysUser> result = new Result<SysUser>();
        if(!VerifyParam.verifyParam("id",id,"SysUser")){
            result.error500("数据范围验证失败！");
            return result;
        }
        SysUser sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysUser);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 查询用户角色
     * @param userid
     * @return
     */
    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/queryUserRole")
    public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        Result<List<String>> result = new Result<>();
        if(!VerifyParam.verifyParam("id",userid,"SysUser")){
            result.error500("数据范围验证失败！");
            return result;
        }
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleId());
            }
            result.setSuccess(true);
            result.setResult(list);
        }
        return result;
    }


    /**
     *  校验用户账号是否唯一<br>
     *  可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(SysUser sysUser) {
        Result<Boolean> result = new Result<>();
        if(!VerifyParam.verifyParam("SysUser",sysUser,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>(sysUser));
            if (user != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * @description: 用于第一次登录修改密码，shiro排除此接口
     * @param jsonObject 1
     * @return org.dfzt.common.api.vo.Result<?>
     * @author cuiyf
     * @date 2020/6/29 17:53
     */
    @RequestMapping(value = "/changePasswordForNewUser", method = RequestMethod.POST)
    public Result<?> changePasswordForNewUser(@RequestBody JSONObject jsonObject) {
        SMUtils.decryptJSONObject(jsonObject);

        if(!VerifyParam.verifyParam("SysUser",jsonObject,"object")){
            return Result.error("数据范围验证失败！");
        }
        SysUser user = sysUserService.getUserByName(jsonObject.getString("username"));

        if (!SMUtils.compareTwoPWD(jsonObject.getString("loginUserPassword"),user.getPassword())){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("用户名或密码不正确!");
        }

        if (SMUtils.compareTwoPWD(jsonObject.getString("password"),
                jsonObject.getString("loginUserPassword"))){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("新密码不能与上次密码相同！");
        }

        if(!SMUtils.compareTwoPWD(jsonObject.getString("password"),
                jsonObject.getString("confirmPassword"))){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("两次输入密码不同！");
        }

        //验证密码是否包含用户名 false为不包含
        if (SMUtils.checkPwdContainsUsername(jsonObject.getString("password"),
                jsonObject.getString("username"))){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("密码不能与用户名相同或包含用户名");
        }


        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, jsonObject.getString("username")));
        if (u == null) {
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("用户名或密码不正确！");
        }
        u.setPassword(jsonObject.getString("password"));
        u.setPasswordUpdateTime(new Date());
        u.setNeedUpdatePw("0");
        return sysUserService.changePassword(u);
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/changePassword")
    public Result<?> changePassword(@RequestBody JSONObject jsonObject) {
        SMUtils.decryptJSONObject(jsonObject);
        if(!VerifyParam.verifyParam("SysUser",jsonObject,"object")){
            return Result.error("数据范围验证失败！");
        }
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();

        if (!SMUtils.compareTwoPWD(jsonObject.getString("loginUserPassword"),user.getPassword())){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("登录用户密码不正确!");
        }

        SysUser sysUser = sysUserService.getUserByName(jsonObject.getString("username"));
        if (SMUtils.compareTwoPWD(jsonObject.getString("password"),
                sysUser.getPassword())){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("新密码不能与上次密码相同！");
        }

        if(!SMUtils.compareTwoPWD(jsonObject.getString("password"),
                jsonObject.getString("confirmPassword"))){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("两次输入密码不同！");
        }

        //验证密码是否包含用户名 false为不包含
        if (SMUtils.checkPwdContainsUsername(jsonObject.getString("password"),
                jsonObject.getString("username"))){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("密码不能与用户名相同或包含用户名");
        }


        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, jsonObject.getString("username")));
        if (u == null) {
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("用户不存在！");
        }
        u.setPassword(jsonObject.getString("password"));
        u.setPasswordUpdateTime(new Date());
        u.setNeedUpdatePw("0");
        return sysUserService.changePassword(u);
    }

    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/userDepartList")
    public Result<List<DepartIdModel>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        Result<List<DepartIdModel>> result = new Result<>();
        if(!VerifyParam.verifyParam("id",userId,"SysUser")){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
            if (depIdModelList != null && depIdModelList.size() > 0) {
                result.setSuccess(true);
                result.setMessage("查找成功");
                result.setResult(depIdModelList);
            } else {
                result.setSuccess(false);
                result.setMessage("查找失败");
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("查找过程中出现了异常: " + e.getMessage());
            return result;
        }

    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    /**
     * 根据部门id查询用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryUserByDepId", method = RequestMethod.GET)
    public Result<List<SysUser>> queryUserByDepId(@RequestParam(name = "id", required = true) String id,@RequestParam(name="realname",required=false) String realname) {
        Result<List<SysUser>> result = new Result<>();
        if(!VerifyParam.verifyParam("id",id,"SysUser")){
            result.error500("数据范围验证失败！");
            return result;
        }
        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        SysDepart sysDepart = sysDepartService.getById(id);
        List<SysUser> userList = sysUserDepartService.queryUserByDepCode(sysDepart.getId(),realname);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
        if(userIds.size() > 0){
            Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            userList.forEach(item->{
                //TODO 临时借用这个字段用于页面展示
                item.setOrgCode(useDepNames.get(item.getId()));
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }

        try {
            result.setSuccess(true);
            result.setResult(userList);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            return result;
        }
    }

    /**
     * 导出excel
     *
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    @RequiresPermissions("url:/sys/user/exportXls")
    public ModelAndView exportXls(SysUser sysUser,HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if(!oConvertUtils.isEmpty(selections)){
            queryWrapper.in("id",selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SysUser> pageList = sysUserService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "用户列表");
        mv.addObject(NormalExcelConstants.CLASS, SysUser.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("用户列表数据", "导出人:"+user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * @功能：根据id 批量查询
     * @param userIds
     * @return
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<SysUser>> queryByIds(@RequestParam String userIds) {
        Result<Collection<SysUser>> result = new Result<>();
        if(!VerifyParam.verifyParam("ids",userIds)){
            result.error500("数据范围验证失败！");
            return result;
        }
        String[] userId = userIds.split(",");
        Collection<String> idList = Arrays.asList(userId);
        Collection<SysUser> userRole = sysUserService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }

    /**
     * 首页用户重置密码
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/updatePassword")
    public Result<?> changPassword(@RequestBody JSONObject json) {
        SMUtils.decryptJSONObject(json);
        //校验老密码是否正确
        String username = json.getString("username");
        String oldPassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmPassword = json.getString("confirmPassword");
        if(!VerifyParam.verifyParam("username",username,"SysUser")
        ||!VerifyParam.verifyParam("password",password,"SysUser")
        ||!VerifyParam.verifyParam("oldpassword",oldPassword)
        ||!VerifyParam.verifyParam("confirmPassword",confirmPassword)){
            return Result.error("数据范围验证失败！");
        }
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        if (!SMUtils.compareTwoPWD(oldPassword,user.getPassword())){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("当前登录密码不正确！");
        }

        if (SMUtils.compareTwoPWD(oldPassword, password)){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("新密码不能与上次密码相同！");
        }

        //验证密码是否包含用户名 false为不包含
        if (SMUtils.checkPwdContainsUsername(password,username)){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("密码不能与用户名相同或包含用户名");
        }

        if(!SMUtils.compareTwoPWD(password,confirmPassword)){
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("两次输入密码不一致！");
        }
        SysUser us = sysUserService.getUserByName(username);
        if(us==null) {
            sysBaseAPI.addLog("用户"+ user.getUsername()+"更新密码失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, user.getUsername());
            return Result.error("用户不存在！");
        }
        return sysUserService.resetPassword(username,password);
    }

    /**
     * 根据角色查询用户
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/userRoleList")
    public Result<IPage<SysUser>> userRoleList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                               @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        if(!VerifyParam.verifyParam("roleId",roleId,"SysUserRole")
        ||(StringUtils.isNotBlank(username)&&!VerifyParam.verifyParam("username",username,"SysUser"))){
            result.error500("数据范围验证失败！");
            return result;
        }

        IPage<SysUser> pageList = sysUserService.getUserByRoleId(page,roleId,username);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    private List<String> roleList(){
        List<SysRole> roles = sysRoleService.list(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, "admin")
                .or()
                .eq(SysRole::getRoleCode, "audit")
                .or().eq(SysRole::getRoleCode, "business_config"));
        return roles.stream().map(SysRole::getId).collect(Collectors.toList());
    }

    /**
     * 给指定角色添加用户
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/addSysUserRole")
    public Result<String> addSysUserRole(@RequestBody SysUserRoleVO sysUserRoleVO) {
        Result<String> result = new Result<>();
        if(!VerifyParam.verifyParam("SysUserRoleVO",sysUserRoleVO,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        List<String> collect = roleList();
        try {
            String sysRoleId = sysUserRoleVO.getRoleId();
            SysRole role = sysRoleService.getById(sysRoleId);
            for(String sysUserId:sysUserRoleVO.getUserIdList()) {
                SysUser one1 = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, sysUserId));
                //根据用户id查出用户角色对应关系
                List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, sysUserId));
                if (list != null && !list.isEmpty()){
                    for (SysUserRole userRole: list){
                        if (collect.contains(userRole.getRoleId())){
                            //遍历集合，如果这个角色id
                            sysBaseAPI.addLog(role.getRoleName()+"添加用户失败", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_FAIL, null);
                            result.setSuccess(false);
                            result.setMessage("添加失败，此用户已被其它角色关联！");
                            return result;
                        }
                    }
                }
                SysUserRole sysUserRole = new SysUserRole(sysUserId,sysRoleId);
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("role_id", sysRoleId).eq("user_id",sysUserId);
                SysUserRole one = sysUserRoleService.getOne(queryWrapper);
                if(one==null){
                    sysUserRoleService.save(sysUserRole);
                    sysBaseAPI.addLog(role.getRoleName()+"角色添加" + one1.getUsername() + "用户成功", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_SUCCESS, null);
                }

            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }
    /**
     *   删除指定角色的用户关系
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/deleteUserRole")
    public Result<SysUserRole> deleteUserRole(@RequestParam(name="roleId") String roleId,
                                              @RequestParam(name="userId",required=true) String userId) {
        Result<SysUserRole> result = new Result<>();
        if(!VerifyParam.verifyParam("roleId",roleId,"SysUserRole")
        || !VerifyParam.verifyParam("userId",userId,"SysUserRole")){
            result.error500("数据范围验证失败！");
            return result;
        }
        SysRole role = sysRoleService.getById(roleId);
        SysUser user = sysUserService.getById(userId);
        try {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).eq("user_id",userId);
            sysUserRoleService.remove(queryWrapper);
            sysBaseAPI.addLog(role.getRoleName()+"角色取消" + user.getUsername() + "用户的授权成功!",CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_SUCCESS, null);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            sysBaseAPI.addLog(role.getRoleName()+"角色取消" + user.getUsername() + "用户的授权失败!",CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_FAIL, null);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.POST)
    @RequiresPermissions("url:/sys/user/deleteUserRoleBatch")
    public Result<SysUserRole> deleteUserRoleBatch(
            @RequestParam(name="roleId") String roleId,
            @RequestParam(name="userIds",required=true) String userIds) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        if(!VerifyParam.verifyParam("roleId",roleId,"SysUserRole")
                ||VerifyParam.verifyParam("ids",userIds)){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).in("user_id",Arrays.asList(userIds.split(",")));
            sysUserRoleService.remove(queryWrapper);
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 部门用户列表
     */
    @RequestMapping(value = "/departUserList", method = RequestMethod.GET)
    @RequiresPermissions("url:/sys/user/departUserList")
    public Result<IPage<SysUser>> departUserList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        String depId = req.getParameter("depId");
        String username = req.getParameter("username");
        if(!VerifyParam.verifyParam("depId",depId,"SysUserDepart")
                ||(StringUtils.isNotBlank(username)&&!VerifyParam.verifyParam("username",username,"SysUser"))){
            result.error500("数据范围验证失败！");
            return result;
        }
        //根据部门ID查询,当前和下级所有的部门IDS
        List<String> subDepids = new ArrayList<>();
        //部门id为空时，查询我的部门下所有用户
        if(oConvertUtils.isEmpty(depId)){
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            int userIdentity = user.getUserIdentity() != null?user.getUserIdentity():CommonConstant.USER_IDENTITY_1;
            if(oConvertUtils.isNotEmpty(userIdentity) && userIdentity == CommonConstant.USER_IDENTITY_2 ){
                subDepids = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
            }
        }else{
            subDepids = sysDepartService.getSubDepIdsByDepId(depId);
        }
        if(subDepids != null && subDepids.size()>0){
            IPage<SysUser> pageList = sysUserService.getUserByDepIds(page,subDepids,username);
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
            if(userIds!=null && userIds.size()>0){
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                pageList.getRecords().forEach(item -> {
                    //批量查询用户的所属部门
                    item.setOrgCode(useDepNames.get(item.getId()));
                    item.setOrgCodeTxt(useDepNames.get(item.getId()));
                });
            }
            result.setSuccess(true);
            result.setResult(pageList);
        }else{
            result.setSuccess(true);
            result.setResult(null);
        }
        return result;
    }


    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 若某个用户包含多个部门，则会显示多条记录，可自行处理成单条记录
     */
    @GetMapping("/queryByOrgCode")
    @RequiresPermissions("url:/sys/user/queryByOrgCode")
    public Result<?> queryByDepartId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode") String orgCode,
            SysUser userParams
    ) {
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, new Page(pageNo, pageSize));
        return Result.ok(pageList);
    }

    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 针对通讯录模块做的接口，将多个部门的用户合并成一条记录，并转成对前端友好的格式
     */
    @GetMapping("/queryByOrgCodeForAddressList")
    public Result<?> queryByOrgCodeForAddressList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode",required = false) String orgCode,
            SysUser userParams
    ) {
        if(!VerifyParam.verifyParam("SysUser",userParams,"object")
        ||VerifyParam.verifyParam("orgCode",orgCode)){
            Result.error("数据范围验证失败！");
            return Result.error("数据范围验证失败！");
        }
        IPage page = new Page(pageNo, pageSize);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
        List<SysUserSysDepartModel> list = pageList.getRecords();

        // 记录所有出现过的 user, key = userId
        Map<String, JSONObject> hasUser = new HashMap<>(list.size());

        JSONArray resultJson = new JSONArray(list.size());

        for (SysUserSysDepartModel item : list) {
            String userId = item.getId();
            // userId
            JSONObject getModel = hasUser.get(userId);
            // 之前已存在过该用户，直接合并数据
            if (getModel != null) {
                String departName = getModel.get("departName").toString();
                getModel.put("departName", (departName + " | " + item.getDepartName()));
            } else {
                // 将用户对象转换为json格式，并将部门信息合并到 json 中
                JSONObject json = JSON.parseObject(JSON.toJSONString(item));
                json.remove("id");
                json.put("userId", userId);
                json.put("departId", item.getDepartId());
                json.put("departName", item.getDepartName());
//                json.put("avatar", item.getSysUser().getAvatar());
                resultJson.add(json);
                hasUser.put(userId, json);
            }
        }

        IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
        result.setRecords(resultJson.toJavaList(JSONObject.class));
        return Result.ok(result);
    }

    /**
     * 给指定部门添加对应的用户
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
    public Result<String> editSysDepartWithUser(@RequestBody SysDepartUsersVO sysDepartUsersVO) {
        Result<String> result = new Result<String>();
        if(!VerifyParam.verifyParam("sysDepartUsersVO",sysDepartUsersVO,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            String sysDepId = sysDepartUsersVO.getDepId();
            for(String sysUserId:sysDepartUsersVO.getUserIdList()) {
                SysUserDepart sysUserDepart = new SysUserDepart(null,sysUserId,sysDepId);
                QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
                queryWrapper.eq("dep_id", sysDepId).eq("user_id",sysUserId);
                SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
                if(one==null){
                    sysUserDepartService.save(sysUserDepart);
                }
            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     *   删除指定机构的用户关系
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.POST)
    public Result<SysUserDepart> deleteUserInDepart(@RequestParam(name="depId") String depId,
                                                    @RequestParam(name="userId",required=true) String userId
    ) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        if(!VerifyParam.verifyParam("depId",depId,"SysUserDepart")
        ||!VerifyParam.verifyParam("userId",userId,"SysUserDepart")){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id",userId);
            boolean b = sysUserDepartService.remove(queryWrapper);
            if(b){
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id",depId));
                List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                if(roleIds != null && roleIds.size()>0){
                    QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                    query.eq("user_id",userId).in("drole_id",roleIds);
                    departRoleUserService.remove(query);
                }
                result.success("删除成功!");
            }else{
                result.error500("当前选中部门与用户无关联关系!");
            }
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定机构的用户关系
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.POST)
    public Result<SysUserDepart> deleteUserInDepartBatch(
            @RequestParam(name="depId") String depId,
            @RequestParam(name="userIds",required=true) String userIds) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        if(!VerifyParam.verifyParam("depId",depId,"SysUserDepart")
                ||!VerifyParam.verifyParam("ids",userIds)){
            result.error500("数据范围验证失败！");
            return result;
        }
        try {
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).in("user_id",Arrays.asList(userIds.split(",")));
            boolean b = sysUserDepartService.remove(queryWrapper);
            if(b){
                departRoleUserService.removeDeptRoleUser(Arrays.asList(userIds.split(",")),depId);
            }
            result.success("删除成功!");
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     *  查询当前用户的所有部门/当前部门编码
     * @return
     */
    @RequestMapping(value = "/getCurrentUserDeparts", method = RequestMethod.GET)
    public Result<Map<String,Object>> getCurrentUserDeparts() {
        Result<Map<String,Object>> result = new Result<Map<String,Object>>();
        try {
            LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
            List<SysDepart> list = this.sysDepartService.queryUserDeparts(sysUser.getId());
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("list", list);
            map.put("orgCode", sysUser.getOrgCode());
            result.setSuccess(true);
            result.setResult(map);
        }catch(Exception e) {
            log.error(e.getMessage(), e);
            result.error500("查询失败！");
        }
        return result;
    }



    /**
     * 用户注册接口
     */
    @PostMapping("/register")
    public Result<Object> userRegister(@RequestBody JSONObject item) {
        log.info("----注册账号----");
        Result<Object> result = new Result<>();
        SMUtils.decryptJSONObject(item);
        SysUser optor = JSON.parseObject(item.toJSONString(), SysUser.class);
        if(!VerifyParam.verifyParam("SysUser",optor,"object")
        ||!VerifyParam.verifyParam("checkCode",item.getString("checkCode"))){
            result.error500("数据范围验证失败！");
            return result;
        }
        String code = String.valueOf(redisUtil.get(optor.getPhone()));

        SysUser sysUser1 = sysUserService.getUserByName(optor.getUsername());
        if (sysUser1 != null) {
            result.setMessage("用户名已注册");
            result.setSuccess(false);
            return result;
        }
        SysUser sysUser2 = sysUserService.getUserByPhone(optor.getPhone());
        if (sysUser2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }

        if(!IdcardUtil.isValidCard(optor.getIdCard())){
            result.error500("身份证号不合法！");
            return result;
        }
        SysUser sysUser3 = sysUserService.getUserByIdCard(optor.getIdCard());
        if (sysUser3 != null) {
            result.setMessage("身份证号已被注册");
            result.setSuccess(false);
            return result;
        }

        if (!code.equals(item.getString("checkCode"))) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }

        try {
            optor.setSex(IdcardUtil.getGenderByIdCard(optor.getIdCard()));
            optor.setBirthday(IdcardUtil.getBirthDate(optor.getIdCard()));
            optor.setStatus(CommonConstant.USER_UNFREEZE);
            optor.setDelFlag(CommonConstant.DEL_FLAG_0);
            optor.setCreateTime(new Date());//设置创建时间
            optor.setActivitiSync(CommonConstant.ACT_SYNC_0);
            sysUserService.addUserWithRole(optor,"ee8626f80f7c2619917b6236f3a7f02b");//默认临时角色 test
            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    /**
     * 根据用户名或手机号查询用户信息
     * @param
     * @return
     */
    @GetMapping("/querySysUser")
    public Result<Map<String, Object>> querySysUser(SysUser sysUser) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        if(!VerifyParam.verifyParam("SysUser",sysUser,"object")){
            result.error500("数据范围验证失败！");
            return result;
        }
        String phone = sysUser.getPhone();
        String username = sysUser.getUsername();
        Map<String, Object> map = new HashMap<String, Object>();
        if (oConvertUtils.isNotEmpty(phone)) {
            SysUser user = sysUserService.getUserByPhone(phone);
            if(user!=null) {
                map.put("username",user.getUsername());
                map.put("phone",user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        if (oConvertUtils.isNotEmpty(username)) {
            SysUser user = sysUserService.getUserByName(username);
            if(user!=null) {
                map.put("username",user.getUsername());
                map.put("phone",user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        result.setSuccess(false);
        result.setMessage("验证失败");
        return result;
    }

    /**
     * 用户手机号验证
     */
    @PostMapping("/phoneVerification")
    public Result<String> phoneVerification(@RequestBody JSONObject jsonObject) {
        Result<String> result = new Result<String>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        if(!VerifyParam.verifyParam("phone",phone,"SysUser")
        ||!VerifyParam.verifyParam("smscode",smscode)){
            result.error500("数据范围验证失败！");
            return result;
        }
        Object code = redisUtil.get(phone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        redisUtil.set(phone, smscode);
        result.setResult(smscode);
        result.setSuccess(true);
        return result;
    }

    /**
     * 用户更改密码
     */
    @PostMapping("/passwordChange")
    public Result<SysUser> passwordChange(@RequestBody JSONObject item) {
        SMUtils.decryptJSONObject(item);
        Result<SysUser> result = new Result<SysUser>();
        SysUser optor = JSON.parseObject(item.toJSONString(), SysUser.class);
        if(!VerifyParam.verifyParam("SysUser",optor,"object")
                ||!VerifyParam.verifyParam("smscode",item.getString("smscode"))){
            result.error500("数据范围验证失败！");
            return result;
        }
        Object object= redisUtil.get(optor.getPhone());
        if(null==object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if(!object.equals(item.getString("smscode"))) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        SysUser sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername,optor.getUsername())
                        .eq(SysUser::getPhone,optor.getPhone()));
        if (sysUser == null) {
            result.setMessage("未找到用户！");
            result.setSuccess(false);
            return result;
        } else {
            sysUser.setPassword(optor.getPassword());
            this.sysUserService.updateById(sysUser);
            sysBaseAPI.addLog("用户"+ sysUser.getUsername()+"更新密码成功", CommonConstant.TYPE_SYSTEM, CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL, null);
            result.setSuccess(true);
            result.setMessage("密码重置完成！");
            return result;
        }
    }


    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public Result<?> getUserSectionInfoByToken(HttpServletRequest request, @RequestParam(name = "token", required = false) String token) {
        try {
            String username = null;
            // 如果没有传递token，就从header中获取token并获取用户信息
            if (oConvertUtils.isEmpty(token)) {
                username = JwtUtil.getUserNameByToken(request);
            } else {
                username = JwtUtil.getUsername(token);
            }

            log.info(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

            // 根据用户名查询用户信息
            SysUser sysUser = sysUserService.getUserByName(username);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sysUserId", sysUser.getId());
            map.put("sysUserCode", sysUser.getUsername()); // 当前登录用户登录账号
            map.put("sysUserName", sysUser.getRealname()); // 当前登录用户真实名称
            map.put("sysOrgCode", sysUser.getOrgCode()); // 当前登录用户部门编号

            log.info(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

            return Result.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @GetMapping("/recycleBin")
    public Result<?> getRecycleBin() {
        List<SysUser> logicDeletedUserList = sysUserService.queryLogicDeleted();
        if (logicDeletedUserList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = logicDeletedUserList.stream().map(SysUser::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            logicDeletedUserList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 还原被逻辑删除的用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.POST)
    public Result<?> putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String userIds = jsonObject.getString("userIds");
        if(!VerifyParam.verifyParam("ids",userIds)){
            return Result.error("数据范围验证失败！");
        }
        if (StringUtils.isNotBlank(userIds)) {
            SysUser updateUser = new SysUser();
            updateUser.setUpdateBy(JwtUtil.getUserNameByToken(request));
            updateUser.setUpdateTime(new Date());
            sysUserService.revertLogicDeleted(Arrays.asList(userIds.split(",")), updateUser);
        }
        return Result.ok("还原成功");
    }

    /**
     * 彻底删除用户
     *
     * @param userIds 被删除的用户ID，多个id用半角逗号分割
     * @return
     */
    @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.POST)
    public Result<?> deleteRecycleBin(@RequestParam("userIds") String userIds) {
        if(!VerifyParam.verifyParam("ids",userIds)){
            return Result.error("数据范围验证失败！");
        }
        String[] arr = userIds.split(",");
        for (String id: arr){
            //查询到用户后判断是否是管理员用户
            if(id.equals(adminId) || id.equals(configId) || id.equals(auditId)){
                return Result.error("禁止删除系统账号！");
            }
        }
        if (StringUtils.isNotBlank(userIds)) {
            sysUserService.removeLogicDeleted(Arrays.asList(userIds.split(",")));
        }
        return Result.ok("删除成功");
    }
}
